<?php
namespace Todo\Controller;

use Todo\PHPExcel\Helper;
use Todo\Service\FileService;

class ApiController extends BaseController
{
    protected $_limit = 1000;
    protected $_order = 'id DESC';
    protected $_field = '*';
    protected $_format = '';
    protected $_page = 1;
    protected $_model;
    protected $_user = null;


    /**
     * Restful风格接口,查询一条数据
     */
    public function read()
    {
        $id = I('get.id');
        if (!$id) $this->apiError('参数不完整');

        $this->_loadModel();
        $data = $this->_model->keyFind($id);
        if (!$data) $this->apiError('数据不存在');

        $this->apiSuccess($data);
    }

    /**
     * 创建一条新数据
     */
    public function create()
    {
        $this->_loadModel();
        $this->_model->startTrans();
        if (method_exists($this->_model, 'insert')) {
            $ret = $this->_model->insert();
        } else {
            $ret = ($this->_model->create() && $this->_model->add() !== false);
        }

        if ($ret === false) {
            $this->_model->rollback();
            $this->apiError('保存失败!' . $this->_model->getError());
        } else {
            $this->_model->commit();
            $this->apiSuccess(null, '保存成功!');
        }
    }

    public function update()
    {
        $this->_loadModel();
        $this->_model->startTrans();
        if (method_exists($this->_model, 'update')) {
            $id = I('post.' . $this->_model->getPk());
            $ret = $this->_model->update($id);
        } else {
            $ret = ($this->_model->create() && $this->_model->save() !== false);
        }
        if ($ret === false) {
            $this->_model->rollback();
            $this->apiError('保存失败!' . $this->_model->getError());
        } else {
            $this->_model->commit();
            $this->apiSuccess(null, '保存成功!');
        }
    }

    /**
     * 删除，支持批量
     */
    public function delete()
    {
        if (IS_GET) {
            $ids = I('get.id');
            if (!$ids) $this->apiError('非法请求!');
        } else {
            $ids = I('post.id');
            if (!$ids) $this->apiError('非法请求!');
        }
        if (is_string($ids)) $ids = explode(',', $ids);
        $this->_loadModel();
        $this->_model->startTrans();
        $total = 0;
        foreach ($ids as $id) {
            $this->_model->del($id) && $total++;
        }
        if ($total == 0) {
            $this->_model->rollback();
            $this->apiError('删除用了' . $total . '条数据');
        }
        $this->_model->commit();
        $this->apiSuccess(null, '删除了' . $total . '条数据');
    }

    /**
     * 分页查询
     */
    public function lists()
    {
        $data = $this->_list();
        $this->apiSuccess($data);
    }

    /**
     * 查询单条数据信息
     */
    public function info()
    {
        $this->read();
    }

    /**
     * 添加
     */
    public function add()
    {
        $this->create();
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $this->update();
    }

    /**
     * 启用，支持批量
     */
    public function enable()
    {
        if (IS_GET) {
            $ids = I('get.id');
            if (!$ids) $this->apiError('非法请求!');
        } else {
            $ids = I('post.id');
            if (!$ids) $this->apiError('非法请求!');
        }
        if (is_string($ids)) $ids = explode(',', $ids);
        $this->_loadModel();
        $this->_model->startTrans();
        $total = 0;
        foreach ($ids as $id) {
            $this->_model->enable($id) && $total++;
        }
        if ($total == 0) {
            $this->_model->rollback();
            $this->apiError('启用了' . $total . '条数据');
        }
        $this->_model->commit();
        $this->apiSuccess(null, '启用了' . $total . '条数据');
    }

    /**
     * 禁用，支持批量
     */
    public function disable()
    {
        if (IS_GET) {
            $ids = I('get.id');
            if (!$ids) $this->apiError('非法请求!');
        } else {
            $ids = I('post.id');
            if (!$ids) $this->apiError('非法请求!');
        }
        if (is_string($ids)) $ids = explode(',', $ids);
        $this->_loadModel();
        $this->_model->startTrans();
        $total = 0;
        foreach ($ids as $id) {
            $this->_model->disable($id) && $total++;
        }
        if ($total == 0) {
            $this->_model->rollback();
            $this->apiError('禁用了' . $total . '条数据');
        }
        $this->_model->commit();
        $this->apiSuccess(null, '禁用了' . $total . '条数据');
    }

    /**
     * 审核
     */
    public function verify()
    {
        if (IS_GET) {
            $ids = I('get.id');
            if (!$ids) $this->apiError('非法请求!');
        } else {
            $ids = I('post.id');
            if (!$ids) $this->apiError('非法请求!');
        }
        if (is_string($ids)) $ids = explode(',', $ids);

        $verifyData = array(
            'verify_status' => I('post.verify_status/d'),
            'verify_user' => auto_login(),
            'verify_time' => auto_datetime(),
            'verify_reason' => I('post.verify_reason')
        );
        $this->_loadModel();
        $this->_model->startTrans();
        $total = 0;
        foreach ($ids as $id) {
            $this->_model->where(array('id' => $id))->save($verifyData) && $total++;
        }
        if ($total == 0) {
            $this->_model->rollback();
            $this->apiError('操作失败!');
        }
        $this->_model->commit();
        $this->apiSuccess(null, '审核了' . $total . '条数据');
    }

    /**
     * 导入数据
     */
    public function import()
    {
        $fileId = I('post.xls_file');
        if (!$fileId) $this->apiError('请先上传文件!');

        $fileInfo = FileService::getInstance()->cacheFindFile($fileId);
        if (!$fileInfo || !FileService::getInstance()->fileExist($fileInfo['path'])) $this->apiError('数据文件不存在，请先上传文件!');

        $xls = new Helper();
        $data = $xls->importExcel(C('FILE_UPLOAD.rootPath') . $fileInfo['path']);
        if (!$data) $this->apiError('解析文件失败:' . $xls->getError());

        $this->_loadModel();
        $ret = $this->_model->import($data[0]["Content"], 2);
        if ($ret === false) {
            $this->apiError('导入数据失败!' . $this->_model->getError());
        } else {
            $this->apiSuccess(null, '成功导入数据' . $ret . '行!');
        }
    }

    /**
     * 通用分页查询，默认查询1000条
     * @return array
     */
    protected function _list()
    {
        $this->_loadModel();
        $where = $this->_search();
        $this->_filter($where);
        $this->_pager();
        $total = $this->_model->pageCount($where);
        $list = $this->_model->field($this->_field)->pageSelect($where, $this->_page, $this->_limit, $this->_order);
        //格式化
        if ($this->_format) foreach ($list as &$row) $this->_model->format($row, $this->_format);
        return array(
            'list' => $list,
            'total' => $total
        );
    }

    /**
     * 根据表单生成查询条件
     * 进行列表过滤
     * @access protected
     * @param  string $name 数据对象名称
     * @return array
     */
    protected function _search($name = '')
    {
        $this->_loadModel();
        $map = array();//$map = array ('terminalId' => TNT_ID);
        foreach ($this->_model->getDbFields() as $key => $val) {
            if (isset ($_REQUEST [$val]) && $_REQUEST [$val] != '') {
                $map [$val] = $_REQUEST [$val];
            }
        }
        if ($map['id'] && is_string($map['id'])) $map['id'] = array('in', explode(',', $map['id']));
        unset($map['sort']);
        return $map;
    }

    /**
     * 自定义查询条件
     * @param array &$where 丢生成的查询条件
     */
    protected function _filter(&$where)
    {
    }

    /**
     * 设置grid的分页信息
     */
    protected function _pager()
    {
        if (isset($_REQUEST['page']) && !empty($_REQUEST['page'])) {
            $this->_page = intval($_REQUEST['page']);
        }

        if (isset($_REQUEST['limit']) && !empty($_REQUEST['limit'])) {
            $this->_limit = intval($_REQUEST['limit']);
        }

        if (isset($_REQUEST['sort']) && !empty($_REQUEST['sort'])) {
            $this->_order = $_REQUEST['sort'];
            if (isset($_REQUEST['order']) && !empty($_REQUEST['order'])) {
                $this->_order .= ' ' . $_REQUEST['order'];
            }
        }
    }

    /**
     * 加载 Model
     *
     */
    protected function _loadModel()
    {
        if (!$this->_model) $this->_model = D('Todo/' . MODULE_NAME . '/' . CONTROLLER_NAME);
    }

    /**
     * 验证权限范围
     * @param string $scope
     * @return bool
     */
    protected function _checkAccess($scope = '')
    {
        //必须要有令牌
        if (!$this->_token) {
            $token = I('post.token/s');
            if (!$token && $scope != 'public') $this->apiError('非法请求，令牌不能为空', 709);
            if ($token) $this->_token = TokenService::getInstance()->getToken($token);
            if (!$this->_token && $scope != 'public') $this->apiError('非法令牌或者已经过期', 709);
        }

        if (!$scope || $scope == 'public') return true;

        if (!TokenService::getInstance()->checkScope($this->_token['code'], $scope)) $this->apiError(TokenService::getInstance()->getError(), 708);

        return true;
    }

    public function getToken()
    {
        $server = $_SERVER;
        $headers = array();
        foreach ($server as $key => $value) {
            if (0 === strpos($key, 'HTTP_')) {
                $headers[substr($key, 5)] = $value;
            }
            elseif (in_array($key, array('CONTENT_LENGTH', 'CONTENT_MD5', 'CONTENT_TYPE'))) {
                $headers[$key] = $value;
            }
        }

        if (isset($server['PHP_AUTH_USER'])) {
            $headers['PHP_AUTH_USER'] = $server['PHP_AUTH_USER'];
            $headers['PHP_AUTH_PW'] = isset($server['PHP_AUTH_PW']) ? $server['PHP_AUTH_PW'] : '';
        } else {
            $authorizationHeader = null;
            if (isset($server['HTTP_AUTHORIZATION'])) {
                $authorizationHeader = $server['HTTP_AUTHORIZATION'];
            } elseif (isset($server['REDIRECT_HTTP_AUTHORIZATION'])) {
                $authorizationHeader = $server['REDIRECT_HTTP_AUTHORIZATION'];
            } elseif (function_exists('apache_request_headers')) {
                $requestHeaders = (array) apache_request_headers();
                $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
                if (isset($requestHeaders['Authorization'])) {
                    $authorizationHeader = trim($requestHeaders['Authorization']);
                }
            }
            if (null !== $authorizationHeader) {
                $headers['AUTHORIZATION'] = $authorizationHeader;
                if (0 === stripos($authorizationHeader, 'basic')) {
                    $exploded = explode(':', base64_decode(substr($authorizationHeader, 6)));
                    if (count($exploded) == 2) {
                        list($headers['PHP_AUTH_USER'], $headers['PHP_AUTH_PW']) = $exploded;
                    }
                }
            }
        }
        if (isset($headers['PHP_AUTH_USER'])) {
            $headers['AUTHORIZATION'] = 'Basic '.base64_encode($headers['PHP_AUTH_USER'].':'.$headers['PHP_AUTH_PW']);
        }
        var_dump($headers);die();
    }

}